#!/usr/bin/env python
import urllib
import sys, math
import os
import threading
import getopt
import platform

try:
    import simplejson as json
except ImportError:
    try:
        import json
    except ImportError:
        print sys.argv[0], " requrires either simplejson module or python > 2.5"
        sys.exit()

art_work_100 = "artworkUrl100"
# KINDS --------------------------------
TV_SHOW     = "tv-episode"
MOVIE       = "feature-movie"
MUSIC_VID   = "music-video"
BOOK        = "book"
ALBUM       = "album"
C_AUDIO     = "coached-audio"
I_BOOK      = "interactive-booklet"
PDF_PODCAST = "pdf podcast"
PODCAST_E   = "podcast-episode"
SOFTWARE    = "software-package"
SONG        = "song"
ARTIST      = "artist"
# END KINDS ----------------------------
COLLECT = "collectionName"
VERSION = "0.0.3"
duplicate = ""
found = 0
KINDS = "book, album, coached-audio, feature-movie, interactive-booklet, music-video, pdf podcast, podcast-episode, software-package, song, tv-episode, artist"
RETRIEVED = "artwork_retrieved"
opts = ""
args = ""
def set_type():
    global type
    type = ''


print "Script Version ", VERSION
#print "You are running on ", platform.system()
if platform.system() == 'Darwin':
    print "You are running on OS X"
elif platform.system() == 'Linux':
    print "You are running on ", platform.system()

if len(sys.argv) < 2:
    print "usage: ", sys.argv[0], "-n <name> (use + instead of space) -t <type>"
    print "   accepted types are: movie, podcast, music, musicVideo, audiobook, shortFilm, tvShow, software, ebook, all"
    sys.exit()
if sys.version_info < (2, 6):
    print "Version mismatch need 2.6.6 got", sys.version_info
    sys.exit()
try:
    opts, args = getopt.getopt(sys.argv[1:],'t:n:')
except getopt.GetoptError, err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"

for o, a in opts:
    if o == '-t':
       type = a
    if o == '-n':
       name = a
   
FILE_NAME = str(name + ".jpg")
FILE_NAME = FILE_NAME.replace('+','_')
FILE_NAME = FILE_NAME.replace(':','_')
FILE_NAME = FILE_NAME.replace('-','_')
FILE_NAME = FILE_NAME.replace('/','_')
FILE_NAME = FILE_NAME.replace('\\','_')
FILE_NAME = FILE_NAME.replace('%20','_')
FILE_NAME = FILE_NAME.replace('@','_')
FILE_NAME = FILE_NAME.replace('"','_')
FILE_NAME = FILE_NAME.replace('<','_')
FILE_NAME = FILE_NAME.replace('>','_')
FILE_NAME = FILE_NAME.replace('*','_')
FILE_NAME = FILE_NAME.replace('|','_')
#print FILE_NAME

url = "http://itunes.apple.com/search?term=" + name + "&media=" + type
print url
result = json.load(urllib.urlopen(url))

number_of_results = result['resultCount']
print "Number of Results" , number_of_results
if number_of_results == 0:
    print "No Results Found, closing.."
    sys.exit()

#begin for loop for look through results
for x in range(number_of_results):
    wrapper = result['results'][x]['wrapperType']
    if wrapper == "track":
        kind = result['results'][x]['kind']
        if kind == TV_SHOW:
            R = result['results'][x]['artworkUrl100']
            X = R.replace('.100x100-75.','.')
            print "Tv-show ", X
            if duplicate == X:
                found = 1
                break
            else:
                duplicate = X
        elif kind == MOVIE:
            R = result['results'][x]['artworkUrl100']
            X = R.replace('.100x100-75.','.')
            print "Movie: ", X
            found = 1
            break
        elif kind == MUSIC_VID:
            print "music video"
        else:
            print kind
            found = 0
    else:
        print "Audiobook"



#end for Loop

#print X
if found == 1:
    print "Found ", FILE_NAME
    FILE_NAME = "./" + FILE_NAME
    urllib.urlretrieve(X, FILE_NAME)


